﻿using Newtonsoft.Json;
using System.Net.Http;

namespace DotNetStar.OpenSDK.QQ
{
    /// <summary>
    /// 获取 OpenId 的 api 模块。
    /// </summary>
    /// <seealso cref="ApiRequest{T}" />
    public class QQOpenIdApiRequest : ApiRequest<QQOpenIdApiResponse>
    {
        /// <summary>
        /// 初始化 <see cref="QQOpenIdApiRequest"/> 类的新实例。
        /// </summary>
        /// <param name="accessToken">令牌凭据。</param>
        public QQOpenIdApiRequest(string accessToken)
            :base("https://graph.qq.com/oauth2.0/me")
        {
            this.AccessToken = accessToken;
        }

        /// <summary>
        /// 获取令牌凭据。
        /// </summary>
        public string AccessToken { get; }

        /// <summary>
        /// 处理自定义请求结果的回调。
        /// </summary>
        /// <param name="httpResponse">Http 请求响应的 <see cref="T:System.Net.Http.HttpResponseMessage" /> 实例。</param>
        /// <returns>
        /// 自定义的处理结果。
        /// </returns>
        public override QQOpenIdApiResponse ResponseHandler(HttpResponseMessage httpResponse)
        { 
            var responseString = httpResponse.GetContentAsString();
            responseString = responseString.Replace("callback(", string.Empty).TrimEnd();
            responseString = responseString.TrimEnd(';');
            responseString = responseString.TrimEnd(')');
            return JsonConvert.DeserializeObject<QQOpenIdApiResponse>(responseString);
        }
    }
}
